//
//  ScanCodeVC.m
//  ShareElectricity
//
//  Created by sunsoft on 2017/6/10.
//  Copyright © 2017年 sunnsoft.HH. All rights reserved.
//

#import "ScanCodeVC.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "LendInformationVC.h"
#import "lendInformationVC1.h"
#import "SEQRView.h"


@interface ScanCodeVC ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic,copy)NSString *urlString;
@property (nonatomic,strong)NSBundle * bundle;
@property (nonatomic, strong) SEQRView *qrView;
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureSession * session;
@property (nonatomic,strong) AVCaptureSession * captureSession;
@property (nonatomic,strong) AVCaptureDevice * captureDevice;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (strong,nonatomic)NSString * uuidStr;
@property (strong,nonatomic)NSString * typeStr;
@property (nonatomic, assign) BOOL isOpen;
@end

@implementation ScanCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isOpen = NO;
    [SEChangeLanguage initUserLanguage];
    _bundle = [SEChangeLanguage bundle];
    self.view.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf = self;
    [HNaviBar customNaviBarWithTitle:[_bundle localizedStringForKey:@"借移動電源" value:nil table:@"Localization"] andLeftEvent:^(UIButton *leftSender) {
        [SVProgressHUD dismiss];
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    } aimView:self.view];
    [self initConfig];
    NotificationCenterADD(self, @selector(ScanQrAgain), NotificatScanQr, nil);
    
}
-(void)ScanQrAgain{
    [self.session startRunning];
    [_qrView show];
}
- (void)initConfig {
    // 检查授权
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {
//        [self showTipLable];
        //        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:mediaType];
    
    NSError *error = nil;
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error) {
        HLog(@"没有摄像头: %@", error.localizedDescription);
        
        [SVProgressHUD showErrorWithStatus:@"设备没有摄像头"];
        
        return;
    }
    
    self.output = [[AVCaptureMetadataOutput alloc] init];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    CGFloat wh = 0; // 有效范围 0 * 0, 居中
    if (self.view.frame.size.width > 320) {
        wh = 250;
    } else {
        wh = 200;
    }
    // 所有扫描范围
    CGFloat supW = self.view.bounds.size.width;
    CGFloat supH = self.view.bounds.size.height;
    // 参数值是 0.0 ~ 1.0, Rect:(y,x,height,width)
    CGFloat width = wh / supW;
    CGFloat height = wh / supH;
    CGFloat x = (supW - wh) * 0.5 / supW;
    CGFloat y = ((supH - wh) * 0.5) / supH;
    // Rect:(y,x,height,width)
    self.output.rectOfInterest = CGRectMake(y, x, height, width);
    
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPreset640x480;
    
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    // 条码类型
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.videoGravity = AVLayerVideoGravityResize;
    self.preview.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // 开始扫码
    [self.session startRunning];
    
    SEQRView *qrView = [[SEQRView alloc] initWithFrame:self.view.bounds];
//    qrView.y -= 64;
    
    CGSize size = CGSizeZero;
    if (self.view.frame.size.width > 320) {
        size = CGSizeMake(250, 250);
    } else {
        size = CGSizeMake(200, 200);
    }
    
    qrView.transparentArea = size;
    qrView.backgroundColor = [UIColor clearColor];
    //    qrView.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
    [self.view insertSubview:qrView atIndex:1];
    self.qrView = qrView;
    
    UIButton * tipsBt = [UIButton new];
    [tipsBt setTitle:[_bundle localizedStringForKey:@"對準設備上的二維碼" value:nil table:@"Localization"] forState:UIControlStateNormal];
    tipsBt.titleLabel.font = HHFont(13);
    [self.view addSubview:tipsBt];
    [tipsBt mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view).offset(qrView.center.y + size.height/2 + 30);
        make.centerX.equalTo(self.view);
        
    }];
    
    UIButton * openLightBt = [UIButton new];
    [openLightBt setBackgroundImage:[UIImage imageNamed:@"scan_tips"] forState:UIControlStateNormal];
    [openLightBt setTitle:[_bundle localizedStringForKey:@"閃光燈" value:nil table:@"Localization"] forState:UIControlStateNormal];
    //    [tipsBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    openLightBt.titleLabel.font = HHFont(13);
    [self.view addSubview:openLightBt];
    [openLightBt mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(tipsBt.mas_bottom).offset(30);
        make.centerX.equalTo(self.view);
        
    }];
    [openLightBt addTarget:self action:@selector(openLight) forControlEvents:UIControlEventTouchUpInside];

}

-(void)openLight{
    
    if (!self.isOpen) {
        if([self.captureDevice hasTorch] && [self.captureDevice hasFlash])
        {
            if(self.captureDevice.torchMode == AVCaptureTorchModeOff)
            {
                [self.captureSession beginConfiguration];
                [self.captureDevice lockForConfiguration:nil];
                [self.captureDevice setTorchMode:AVCaptureTorchModeOn];
                [self.captureDevice setFlashMode:AVCaptureFlashModeOn];
                [self.captureDevice unlockForConfiguration];
                [self.captureSession commitConfiguration];
            }
        }
        [self.captureSession startRunning];
        self.isOpen = YES;
    } else {
        
        [self.captureSession beginConfiguration];
        [self.captureDevice lockForConfiguration:nil];
        if(self.captureDevice.torchMode == AVCaptureTorchModeOn)
        {
            [self.captureDevice setTorchMode:AVCaptureTorchModeOff];
            [self.captureDevice setFlashMode:AVCaptureFlashModeOff];
        }
        [self.captureDevice unlockForConfiguration];
        [self.captureSession commitConfiguration];
        [self.captureSession stopRunning];
        self.isOpen = NO;
    }

    
}
-(AVCaptureSession *)captureSesion
{
    if(_captureSession == nil)
    {
        _captureSession = [[AVCaptureSession alloc] init];
    }
    return _captureSession;
}

-(AVCaptureDevice *)captureDevice
{
    if(_captureDevice == nil)
    {
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _captureDevice;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    if (metadataObjects.count > 0) {
        // 播放音效
        AudioServicesPlaySystemSound(1000);
        [self.qrView stop];
        [self.session stopRunning];
        AVMetadataMachineReadableCodeObject *metaDataObject = [metadataObjects firstObject];
        
        self.urlString = metaDataObject.stringValue;
        HLog(@"-----%@",self.urlString);
        if ([self.urlString length] > 0) {
  
            NSArray *array = [self.urlString componentsSeparatedByString:@"?"];
            //从字符A中分隔成2个元素的数组
            for (int i =0 ; i < array.count; i ++) {
                if([[array objectAtIndex:i] rangeOfString:@"uuid="].location !=NSNotFound)
                {
                    NSArray *array1 = [[array objectAtIndex:i] componentsSeparatedByString:@"&"];
                    for (int j =0; j<array1.count; j ++) {
                        
                        if([[array1 objectAtIndex:j] rangeOfString:@"uuid="].location !=NSNotFound)
                        {
                            
                            _uuidStr = [[array1 objectAtIndex:j] substringFromIndex:5];

                        }else if([[array1 objectAtIndex:j] rangeOfString:@"type="].location !=NSNotFound)
                        {
                            
                            _typeStr = [[array1 objectAtIndex:j] substringFromIndex:5];
                            
                        }
                    }
                }
                
            }


            if (_typeStr.integerValue == 1) {
                
                LendInformationVC * lvc = [[LendInformationVC alloc] init];
                lvc.uuidStr = _uuidStr;
                lvc.typeStr = _typeStr;
                lvc.fd_prefersNavigationBarHidden = YES;
                [self.navigationController pushViewController:lvc animated:YES];
            }else if(_typeStr.integerValue == 2){
                
                lendInformationVC1 * lvc = [[lendInformationVC1 alloc] init];
                lvc.fd_prefersNavigationBarHidden = YES;
                lvc.uuidStr = _uuidStr;
                lvc.typeStr = _typeStr;
                [self.navigationController pushViewController:lvc animated:YES];
            }else{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD showSuccessWithStatus:[_bundle localizedStringForKey:@"請掃描正確二維碼" value:nil table:@"Localization"]];
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } else {
            [self dismissViewControllerAnimated:NO completion:nil];
        }

    }
}

#pragma mark - UIAction

- (void)leftBarButtonAction {
    
    [SVProgressHUD dismiss];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
